<template>
  <el-dropdown @command="handleCommand" trigger="click" class="user-dropdown" size="large">
    <span class="el-dropdown-link user-info">
      <el-avatar src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" size="small" />
      <span class="username">{{ user_name }}</span>
      <i class="el-icon-arrow-down el-icon--right"></i>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="logout">
          <el-icon>
            <SwitchButton />
          </el-icon>
          登出
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { SwitchButton } from '@element-plus/icons-vue'
import { loginout } from '@/api'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'

const user = useUserStore()
const router = useRouter()
const user_name = ref('')

function handleCommand(command) {
  if (command === 'logout') {
    handleLogout()
  }
}

// 处理登出操作，增加错误处理和加载状态
async function handleLogout() {
  try {
    // 显示加载状态
    const logoutButton = document.querySelector('.el-dropdown-item[command="logout"]')
    if (logoutButton) {
      logoutButton.classList.add('is-disabled')
    }

    // 请求后台
    const currentUser = user.getUser()

    // 检查用户信息是否存在
    if (currentUser && currentUser.user_id) {
      await loginout(currentUser.user_id)
    } else {
      console.warn('用户信息不完整，直接登出')
    }

    // 清空用户信息
    user.$reset()
    sessionStorage.removeItem('token')

    // 跳转到登录页
    router.push('/login')

    // 显示成功消息
    ElMessage.success('登出成功')
  } catch (error) {
    console.error('登出失败:', error)
    ElMessage.error('登出失败，请重试')
  } finally {
    // 恢复按钮状态
    setTimeout(() => {
      const logoutButton = document.querySelector('.el-dropdown-item[command="logout"]')
      if (logoutButton) {
        logoutButton.classList.remove('is-disabled')
      }
    }, 300)
  }
}

onMounted(() => {
  try {
    const currentUser = user.getUser()
    if (currentUser && currentUser.user_name) {
      user_name.value = currentUser.user_name
    } else {
      user_name.value = '未知用户'
      console.warn('未获取到用户信息')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    user_name.value = '未知用户'
  }
})
</script>

<style scoped>
.user-dropdown {
  cursor: pointer;
  height: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  user-select: none;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.user-info:hover {
  background-color: rgba(0, 0, 0, 0.02);
  color: #409eff;
}

.username {
  font-weight: 500;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>